<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Exceptions\ApiRequestException;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;


class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
    public function handle($request, Closure $next,...$guards)
    {
        $token = JWTAuth::getToken();
//        $data = JWTAuth::getPayload();


        // 参数无效huo
        if (!$token) {
            throw  new ApiException('登录错误！',1402);
        }

        try {
            if (!$user = JWTAuth::toUser()){
                throw  new ApiException(' 无此用户',1404);
            }
        } catch (TokenExpiredException $e) {

            throw  new ApiException('登录已 过期',1404);

        } catch (TokenInvalidException $e) {

            throw  new ApiException('登录已 失效',1403);

        } catch (JWTException $e) {

            throw  new ApiException('登录已 参数错误！',1402);

        }
          return $next($request);
    }
}
